<template>
  <div class="pagination">
    <button @click="changepageno(pageNo - 1)" :disabled="pageNo === 1">
      上一页
    </button>
    <button @click="changepageno(1)" v-show="startEnd.start !== 1">1</button>
    <span v-show="startEnd.start > 2">···</span>

    <button
      :class="{ active: pageNo === index + startEnd.start }"
      v-for="(n, index) in startEnd.end - startEnd.start + 1"
      @click="changepageno(index + startEnd.start)"
    >
      {{ index + startEnd.start }}
    </button>

    <span v-show="totalSize - 1 > startEnd.end">···</span>
    <button
      @click="changepageno(totalSize)"
      v-show="startEnd.end !== totalSize"
    >
      {{ totalSize }}
    </button>
    <button @click="changepageno(pageNo + 1)" :disabled="pageNo === totalSize">
      下一页
    </button>

    <span>共 {{ total }} 条</span>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: {
    total: {
      required: true,
    },
    pageNo: {
      required: true,
      type: Number,
    },
    continues: {
      type: Number,
      default: 5,
    },
    pageSize: {
      type: Number,
      required: true,
    },
    changepageno: {
      type: Function,
      required: true,
    },
  },
  computed: {
    // 总页码
    totalSize() {
      // 解构
      let { total, pageSize } = this;
      return Math.ceil(total / pageSize);
    },
    // 计算连续页吗
    startEnd() {
      // 解构
      let { total, pageSize, pageNo, continues, totalSize } = this;
      let start;
      let end;
      if (continues > totalSize) {
        start = 1;
        end = totalSize;
      } else {
        start = pageNo - (continues - 1) / 2;
        end = pageNo + (continues - 1) / 2;
        if (start < 1) {
          start = 1;
          end = continues;
        }
        //当正常计算的end的值 大于 totalSize
        if (end > totalSize) {
          start = totalSize - continues + 1;
          end = totalSize;
        }
      }

      return { start, end };
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;

  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: gray;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #c81623;
      color: #fff;
    }
  }

  span {
    display: inline-block;
    line-height: 28px;
    font-size: 14px;
    color: gray;
    vertical-align: middle;
  }
}
</style>
